const { app, BrowserWindow , ipcMain, dialog, Menu, MessageChannelMain, Notification } = require('electron/main')
const path = require('node:path')
const utils = require("./utils")
const { download } = require("./download/index")
const DOWNLOAD = new download()

const createWindow = () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  win.loadFile('index.html')


  const {port1, port2} = new MessageChannelMain();
  win.webContents.postMessage('chanal', null, [port1])
  port1.postMessage({some: "message"})

   new Notification({title:"通知标题", body:"通知主体", closeButtonText:"关闭"})
}

app.whenReady().then(() => {
  ipcMain.handle('ping', () => '调用ping打印出pong')
  ipcMain.handle('msg',  async (event, args)=> {
    const r = await utils.httpSend(args);
    return r
  });

  ipcMain.on("port", (e, msg) => {
    const [port] = e.ports;
    // console.log("port", port, msg)
    const r = {port, msg}
    console.log("msg.message", msg.message)
    return msg.message
  });

  const openNativeFile = async () => {
    let result
    await dialog.showOpenDialog({title:"这是标题",properties: ["openFile", 'multiSelections'],message:"这是信息"}, async (res) => {
      console.log("这是打开的文件", res)
      result = res
    });
    return result;
  }

  ipcMain.handle('openFile', async () => {
    const r = await openNativeFile();
    return r;
  })


  ipcMain.on("show-context-menu", (event) => {
    const template = [
      {
        label: 'Menu Item 1',
        click: () => { event.sender.send('context-menu-command', 'menu-item-1') }
      },
      { type: 'separator' },
      { label: 'Menu Item 2', type: 'checkbox', checked: true }
    ]
    const menu = Menu.buildFromTemplate(template)
    menu.popup({ window: BrowserWindow.fromWebContents(event.sender) })
  })
  

  ipcMain.on('show-context-menu', (event) => {
    const template = [
      {
        label: 'Menu Item 1',
        click: () => { event.sender.send('context-menu-command', 'menu-item-1') }
      },
      { type: 'separator' },
      { label: 'Menu Item 2', type: 'checkbox', checked: true }
    ];
    console.log("这是菜单", template)
    const menu = Menu.buildFromTemplate(template)
    // Menu.setApplicationMenu(menu)
    menu.popup({ window: BrowserWindow.fromWebContents(event.sender) })
  })


ipcMain.handle('download', () => {
    DOWNLOAD.start();
})

ipcMain.handle('pause', () => {
    DOWNLOAD.pauseDownload()
})

ipcMain.handle('unpause', () => {
  DOWNLOAD.resumeDownload()
})


  createWindow()





  
 

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})